'use strict';
const db = uniCloud.database()
const dbHelper = require("db-helper")
const orderHelper = require("order-helper")
const md5 = require("md5-node")
exports.main = async (event, context) => {
	//const res= "{\"msg\":\"{\\\"appid\\\":\\\"ttc46fb2d25b563c6601\\\",\\\"cp_orderno\\\":\\\"0a4ec1f9629ef65a092ee1792153d259\\\",\\\"cp_extra\\\":\\\"\\\",\\\"way\\\":\\\"1\\\",\\\"channel_no\\\":\\\"4317101093202206079556196369\\\",\\\"channel_gateway_no\\\":\\\"\\\",\\\"payment_order_no\\\":\\\"PCP2022060714555400687027319652\\\",\\\"out_channel_order_no\\\":\\\"4317101093202206079556196369\\\",\\\"total_amount\\\":1,\\\"status\\\":\\\"SUCCESS\\\",\\\"seller_uid\\\":\\\"70885543135802514060\\\",\\\"extra\\\":\\\"\\\",\\\"item_id\\\":\\\"\\\",\\\"paid_at\\\":1654584967,\\\"message\\\":\\\"\\\",\\\"order_id\\\":\\\"7106387523878045967\\\",\\\"trade_item_list\\\":null}\",\"msg_signature\":\"c178a8a1a6f57c2884b5d91bd301f22d1812db5f\",\"nonce\":\"3034\",\"timestamp\":\"1654584968\",\"type\":\"payment\"}"
	// const order11=JSON.parse(event.body)
	const res=JSON.parse(event.body)
		
	const ttorder=(JSON.parse(res.msg));
		try{
			const params = {
				"app_id": "ttc46fb2d25b563c6601",
				"out_order_no": ttorder.cp_orderno,
			}
			
			var skip_arr = ["thirdparty_id", "app_id", "sign"];
			var paramArray = new Array();
			for (var k in params) {
				if (skip_arr.indexOf(k) != -1) {
					continue;
				}
				if (params[k] == "") {
					continue;
				}
				paramArray.push(params[k]);
			}
			paramArray.push("9yTlZfGgRntRbkgU8Kr4glsETNOHfjbKZKzKDlie");
			paramArray.sort();
			var signStr = paramArray.join("&");
			params.sign = md5(signStr)
			let resp =await uniCloud.httpclient.request(
				"https://developer.toutiao.com/api/apps/ecpay/v1/query_order", {
					method: 'POST',
					data: params,
					contentType: 'json', // 指定以application/json发送data内的数据
					dataType: 'json' // 指定返回值为json格式，自动进行parse
				})
				console.log(resp.data.payment_info.order_status)
				
				
				if(resp.data.payment_info.order_status=='SUCCESS'){
					var order = await dbHelper.getById("t3ds-order", ttorder.cp_orderno)
					console.log(order)
					if (!order) {
						return {
							err_no: 400,
							err_tips: '订单不存在'
						}
					
				}else{
					console.log('---------update order-------')
					 orderHelper.handleOrderPaid(ttorder.cp_orderno, Date.now())
					order = await dbHelper.getById("t3ds-order", ttorder.cp_orderno)
					console.log(`订单更新完成，状态：${order.status}`)
					return{
						err_no: 0,
						err_tips: 'success'
					}
				}
				}
		}catch(err){
			console.log("回调遇到错误", err)
			return{
				err_no: 400,
				err_tips: 'business fail'
			}
		};
		
	
	};

	
// };
// 	//获取头条支付状态
	function getTtQuerystate(out_order_no){
		const params = {
			"app_id": "ttc46fb2d25b563c6601",
			"out_order_no": out_order_no,
		}
		params.sign = this.ttPayMd5(params)
		let resp = uniCloud.httpclient.request(
			"https://developer.toutiao.com/api/apps/ecpay/v1/query_order", {
				method: 'POST',
				data: params,
				contentType: 'json', // 指定以application/json发送data内的数据
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			})
		return resp
	};
// 	// 计算头条请求签名sign
function	ttPayMd5(params){
		var skip_arr = ["thirdparty_id", "app_id", "sign"];
		var paramArray = new Array();
		for (var k in params) {
			if (skip_arr.indexOf(k) != -1) {
				continue;
			}
			if (params[k] == "") {
				continue;
			}
			paramArray.push(params[k]);
		}
		paramArray.push("9yTlZfGgRntRbkgU8Kr4glsETNOHfjbKZKzKDlie");
		paramArray.sort();
		var signStr = paramArray.join("&");
		return md5(signStr);
	}